﻿using Shop.DAL;
using Shop.Models;
using Shop.Models.DTO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Shop.BLL
{
    public class OrderManager
    {
        BaseService<Orders> ordersService=new BaseService<Orders>();
        BaseService<OrderDetail> detailService=new BaseService<OrderDetail>();
        BaseService<Users> usersService=new BaseService<Users>();

        /// <summary>
        /// 使用事务保存订单和订单明细
        /// </summary>
        /// <param name="dto"></param>
        /// <returns>返回订单号</returns>
        public int SaveOrder(OrderPostDto dto)
        {
            SqlConnection conn=new SqlConnection(SqlHelper.connStr);
            // 插入订单表
            string sql = "insert into [Orders] (userid,state,createat,address,sumprice) values(@userid,0,getdate(),@address,@sumprice); select @@identity";
            SqlParameter[] sp =
            {
                new SqlParameter("@userid",dto.UserId),
                new SqlParameter("@address",dto.Address),
                new SqlParameter("@sumprice",dto.SumPrice),
            };
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddRange(sp);
           
            SqlTransaction trans = null;// 事务对象
            int orderid;
            try
            {
                conn.Open();
                trans = conn.BeginTransaction();// 开始事务
                cmd.Transaction = trans;
                orderid = Convert.ToInt32(cmd.ExecuteScalar());

                // 插入订单明细
                
                foreach (var item in dto.Details)
                {
                    sql = $"insert into [OrderDetail](orderid,productinfoid,count,price,ProductInfoName,Specs,Pictrue) values({orderid},@productinfoid,@count,@price,@ProductInfoName,@Specs,@Pictrue)";
                    SqlParameter[] sps =
                    {
                        new SqlParameter("@productinfoid",item.ProductInfoId),
                        new SqlParameter("@count",item.Count),
                        new SqlParameter("@price",item.Price),
                        new SqlParameter("@ProductInfoName",item.ProductInfoName),
                        new SqlParameter("@Specs",item.Color),
                        new SqlParameter("@Pictrue",item.Image)
                    };
                    SqlCommand command = new SqlCommand(sql, conn);
                    command.Parameters.AddRange(sps);
                    command.Transaction=trans;
                    command.ExecuteNonQuery();
                }
                trans.Commit();
               
            }
            catch
            {
                // 回滚事务
                trans.Rollback();
                return 0;
            }
            return orderid;    
        }

        /// <summary>
        /// 更改订单状态
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public int ChangeOrderState(int orderid,int state)
        {
            var sql = "update orders set state=@state where id=@id";
            SqlParameter[] sp =
            {
                new SqlParameter("@state",state),
                new SqlParameter("@id",orderid)
            };
            return SqlHelper.ExecuteNonQuery(sql,sp);
        }

        /// <summary>
        /// 根据状态查看订单信息（后台用）
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public List<OrderList> GetOrderList(int state,int pageIndex,out int total)
        {
            string where = string.Empty;
            SqlParameter[] sp=null;
            if (state != -1)
            {
                where = "state=@state";
                sp = new SqlParameter[]{ new SqlParameter("@state", state) };
            }
           
            var orders = ordersService.GetList(where, sp, pageIndex, 5,out total);
            List<OrderList> list=new List<OrderList>();
       
            foreach (var order in orders)
            {
                var item = new OrderList();
                item.Id=order.Id; 
                item.Address=order.Address;
                item.CreateAt=order.CreateAt;
                item.SumPrice=order.SumPrice;
                item.State=order.State;
                item.UserName = usersService.GetEntity(order.UserId).Name;

                item.Details = detailService.GetList("orderid=" + order.Id, null);

                list.Add(item);

            }
            return list;

        }
    }
}
